<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

use Yii;
use DateTime;
use DateTimeZone;

/**
 * 时间日期
 * @author cleverstone
 * @since ym2.0
 */
class T
{
    /**
     * 当前时间/日期
     * @param bool|string $toString
     * - bool   是否转字符串，是：Y-m-d H:i:s 否：当前时间戳
     * - string 格式化字符，如：Y.m.d
     *
     * @param string $timeZone 时区，默认跟随框架
     * @return int|string
     * @throws \Exception
     */
    public static function now($toString = true, $timeZone = '')
    {
        $datetime = new DateTime('now', new DateTimeZone($timeZone ?: Yii::$app->timeZone));

        if ($toString === true) {
            return $datetime->format('Y-m-d H:i:s');
        } elseif (is_string($toString)) {
            return $datetime->format($toString);
        } else {
            return $datetime->getTimestamp();
        }
    }

    /**
     * Calculate total number of days between the two dates.
     *
     * @param string $d1 the date
     * @param string $d2 other date
     * @return int
     * @throws \Exception
     */
    public static function spansDays($d1, $d2)
    {
        $dt1 = new DateTime($d1);
        $dt2 = new DateTime($d2);
        $di = $dt1->diff($dt2);

        return $di->days + 1;
    }
}